package com.macro.mall.portal.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.macro.mall.common.service.RedisService;
import com.macro.mall.common.util.StringIf;
import com.macro.mall.mapper.OmsCartItemMapper;
import com.macro.mall.mapper.PmsMemberPriceMapper;
import com.macro.mall.mapper.PmsProductMapper;
import com.macro.mall.mapper.UmsMemberMapper;
import com.macro.mall.model.*;
import com.macro.mall.portal.dao.PortalProductDao;
import com.macro.mall.portal.dao.PortalSkuStockDao;
import com.macro.mall.portal.domain.CartProduct;
import com.macro.mall.portal.domain.CartPromotionItem;
import com.macro.mall.portal.domain.CombinedPmsProduct;
import com.macro.mall.portal.dto.OmsCartItemDto;
import com.macro.mall.portal.service.OmsCartItemService;
import com.macro.mall.portal.service.OmsPromotionService;
import com.macro.mall.portal.service.UmsMemberService;
import com.quyum.mall.market.config.RedisKey;
import com.quyum.mall.market.entity.MarketSmsRound;
import com.quyum.mall.market.entity.MarketSmsRoundProduct;
import com.quyum.mall.market.mapper.MarketSmsRoundMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 购物车管理Service实现类
 * Created by macro on 2018/8/2.
 */
@Service
public class OmsCartItemServiceImpl implements OmsCartItemService {
    @Autowired
    private OmsCartItemMapper cartItemMapper;
    @Autowired
    private PortalProductDao productDao;
    @Autowired
    private OmsPromotionService promotionService;
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PortalSkuStockDao portalSkuStockDao;
    @Autowired
    private RedisService redisService;
    @Autowired
    private MarketSmsRoundMapper roundMapper;
    @Autowired
    private PmsMemberPriceMapper priceMapper;

    @Override
    public int add(OmsCartItem cartItem) {
        int count;
        UmsMember currentMember = memberService.getCurrentMember();
        cartItem.setMemberId(currentMember.getId());
        cartItem.setMemberNickname(currentMember.getNickname());
        cartItem.setDeleteStatus(0);
        OmsCartItem existCartItem = getCartItem(cartItem);
        if (existCartItem == null) {
            cartItem.setCreateDate(new Date());
            count = cartItemMapper.insert(cartItem);
        } else {
            cartItem.setModifyDate(new Date());
            existCartItem.setQuantity(existCartItem.getQuantity() + cartItem.getQuantity());
            count = cartItemMapper.updateByPrimaryKey(existCartItem);
        }
        return count;
    }

    /**
     * 根据会员id,商品id和规格获取购物车中商品
     */
    private OmsCartItem getCartItem(OmsCartItem cartItem) {
        OmsCartItemExample example = new OmsCartItemExample();
        OmsCartItemExample.Criteria criteria = example.createCriteria().andMemberIdEqualTo(cartItem.getMemberId())
                .andProductIdEqualTo(cartItem.getProductId()).andDeleteStatusEqualTo(0);
        if (!StringUtils.isEmpty(cartItem.getProductSkuId())) {
            criteria.andProductSkuIdEqualTo(cartItem.getProductSkuId());
        }
        List<OmsCartItem> cartItemList = cartItemMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(cartItemList)) {
            return cartItemList.get(0);
        }
        return null;
    }

    @Override
    public List<OmsCartItem> getList(Long memberId) {
        OmsCartItemExample example = new OmsCartItemExample();
        example.createCriteria().andDeleteStatusEqualTo(0).andMemberIdEqualTo(memberId);
        return cartItemMapper.selectByExample(example);
    }

    @Override
    public List<OmsCartItemDto> list(Long memberId) {
        UmsMember currentMember = memberService.getCurrentMember();
        List<OmsCartItemDto> result = new ArrayList<>();
        List<OmsCartItem> list = this.getList(memberId);
        List<Long> productIds = list.stream().map(OmsCartItem::getProductId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(productIds)) {
            return new ArrayList<OmsCartItemDto>();
        }
        PmsProductExample productExample = new PmsProductExample();
        productExample.createCriteria().andIdIn(productIds);
        Map<Long, List<PmsProduct>> productIdMap = this.productMapper.selectByExample(productExample).stream().collect(Collectors.groupingBy(PmsProduct::getId));
        for (OmsCartItem item : list) {
            boolean flag = false;
            OmsCartItemDto omsCartItemDto = new OmsCartItemDto();
            BeanUtils.copyProperties(item, omsCartItemDto);
            List<PmsProduct> pmsProducts = productIdMap.get(item.getProductId());
            Integer type = 0;
            if (pmsProducts != null && pmsProducts.get(0) != null && pmsProducts.get(0).getType().equals(1)) {
                List<Long> parentIds = new ArrayList<>();
                parentIds.add(item.getProductSkuId());
                List<CombinedPmsProduct> combinedPmsProductList = this.portalSkuStockDao.queryProductsByCombineParentIds(parentIds);
                if (!CollectionUtils.isEmpty(combinedPmsProductList)) {
                    omsCartItemDto.setCombinedPmsProduct(combinedPmsProductList.get(0));
                    type = 1;
                } else {
                    CombinedPmsProduct combinedPmsProduct = new CombinedPmsProduct();
                    BeanUtils.copyProperties(pmsProducts.get(0), combinedPmsProduct);
                    omsCartItemDto.setCombinedPmsProduct(combinedPmsProduct);
                }
            } else {
                flag = true;
                CombinedPmsProduct combinedPmsProduct = new CombinedPmsProduct();
                BeanUtils.copyProperties(pmsProducts.get(0), combinedPmsProduct);
                omsCartItemDto.setCombinedPmsProduct(combinedPmsProduct);
            }
            String skuStockKey = new StringBuffer(RedisKey.ROUND_SKU_STOCK_KEY).append(item.getProductId()).append("_").append(item.getProductSkuId()).toString();
            Object o = this.redisService.get(skuStockKey);
            if(o!=null){
                MarketSmsRoundProduct roundProduct= (MarketSmsRoundProduct)o;
                type = roundProduct.getType();
                MarketSmsRound marketSmsRound = this.roundMapper.selectByPrimaryKey(roundProduct.getRoundId());
                omsCartItemDto.setActivityEndTime(marketSmsRound.getEndTime());
                omsCartItemDto.setPrice(roundProduct.getActivityPrice());
            }else if (currentMember.getMemberLevel() != null && currentMember.getMemberLevel() != 1 && currentMember.getMemberLevelEndTime().after(new Date())){
                if (flag) {
                    //普通商品
                    PmsMemberPriceExample priceExample = new PmsMemberPriceExample();
                    priceExample.createCriteria().andProductStockIdEqualTo(item.getProductSkuId());
                    List<PmsMemberPrice> pmsMemberPrices = priceMapper.selectByExample(priceExample);
                    omsCartItemDto.setPrice(pmsMemberPrices.get(0).getMemberPrice());
                }
            }
            omsCartItemDto.setType(type);
            result.add(omsCartItemDto);
        }
//        List<OmsCartItemDto> result = new ArrayList<>();
//        List<OmsCartItemProductDto> normal = new ArrayList<>();
//        List<OmsCartItemProductDto> group = new ArrayList<>();
//        OmsCartItemExample example = new OmsCartItemExample();
//        example.createCriteria().andDeleteStatusEqualTo(0).andMemberIdEqualTo(memberId);
//        List<OmsCartItem> omsCartItems = cartItemMapper.selectByExample(example);
//        if(!CollectionUtils.isEmpty(omsCartItems)){
//            for(OmsCartItem omsCartItem : omsCartItems){
//                PmsProduct product = productMapper.selectByPrimaryKey(omsCartItem.getProductId());
//
//                if(product.getType().equals(1)){
//                    group.add(omsCartItem);
//                }else if(product.getType().equals(0)){
//                    normal.add(omsCartItem);
//                }
//            }
//            OmsCartItemDto normalDto = new OmsCartItemDto();
//            OmsCartItemDto groupDto = new OmsCartItemDto();
//            normalDto.setType(0);
//            normalDto.setItems(normal);
//            groupDto.setType(1);
//            groupDto.setItems(group);
//            result.add(groupDto);
//            result.add(normalDto);
//        }
        return result;
    }

    @Override
    public List<CartPromotionItem> listPromotion(Long memberId, List<Long> cartIds, Long storeId) {
        List<OmsCartItem> cartItemList = this.getList(memberId);
        if (CollUtil.isNotEmpty(cartIds)) {
            cartItemList = cartItemList.stream().filter(item -> cartIds.contains(item.getId())).collect(Collectors.toList());
        }
        List<CartPromotionItem> cartPromotionItemList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(cartItemList)) {
            cartPromotionItemList = promotionService.calcCartPromotion(memberId, cartItemList, storeId);
        }
        return cartPromotionItemList;
    }

    @Override
    public int updateQuantity(Long id, Long memberId, Integer quantity) {
        OmsCartItem cartItem = new OmsCartItem();
        if (quantity == null) {
            quantity = 1;
        }
        cartItem.setQuantity(quantity);
        OmsCartItemExample example = new OmsCartItemExample();
        example.createCriteria().andDeleteStatusEqualTo(0)
                .andIdEqualTo(id).andMemberIdEqualTo(memberId);
        return cartItemMapper.updateByExampleSelective(cartItem, example);
    }

    @Override
    public int delete(Long memberId, String ids) {
        List<Long> cartIds = StringIf.getList4Long(ids);
        OmsCartItem record = new OmsCartItem();
        record.setDeleteStatus(1);
        OmsCartItemExample example = new OmsCartItemExample();
        example.createCriteria().andIdIn(cartIds).andMemberIdEqualTo(memberId);
        return cartItemMapper.updateByExampleSelective(record, example);
    }

    @Override
    public CartProduct getCartProduct(Long productId) {
        return productDao.getCartProduct(productId);
    }

    @Override
    public int updateAttr(OmsCartItem cartItem) {
        //删除原购物车信息
        OmsCartItem updateCart = new OmsCartItem();
        updateCart.setId(cartItem.getId());
        updateCart.setModifyDate(new Date());
        updateCart.setDeleteStatus(1);
        cartItemMapper.updateByPrimaryKeySelective(updateCart);
        cartItem.setId(null);
        add(cartItem);
        return 1;
    }

    @Override
    public int clear(Long memberId) {
        OmsCartItem record = new OmsCartItem();
        record.setDeleteStatus(1);
        OmsCartItemExample example = new OmsCartItemExample();
        example.createCriteria().andMemberIdEqualTo(memberId);
        return cartItemMapper.updateByExampleSelective(record, example);
    }
}
